3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Shell
;
24 use MediaWiki\ProcOpenError
;
25 use MediaWiki\ShellDisabledError
;
27 use Psr\Log\LoggerAwareTrait
;
28 use Psr\Log\NullLogger
;
31 * Class used for executing shell commands
39 private $command = '';
60 private $useStderr = false;
63 private $everExecuted = false;
65 /** @var string|false */
66 private $cGroup = false;
69 * Constructor. Don't call directly, instead use Shell::command()
71 * @throws ShellDisabledError
73 public function __construct() {
74 if ( Shell
::isDisabled() ) {
75 throw new ShellDisabledError();
78 $this->setLogger( new NullLogger() );
82 * Destructor. Makes sure programmer didn't forget to execute the command after all
84 public function __destruct() {
85 if ( !$this->everExecuted
) {
86 $message = __CLASS__
. " was instantiated, but execute() was never called.";
87 if ( $this->method
) {
88 $message .= " Calling method: {$this->method}.";
90 $message .= " Command: {$this->command}";
91 trigger_error( $message, E_USER_NOTICE
);
96 * Adds parameters to the command. All parameters are sanitized via Shell::escape().
98 * @param string|string[] $args,...
101 public function params( /* ... */ ) {
102 $args = func_get_args();
103 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
104 // If only one argument has been passed, and that argument is an array,
105 // treat it as a list of arguments
106 $args = reset( $args );
108 $this->command
.= ' ' . Shell
::escape( $args );
114 * Adds unsafe parameters to the command. These parameters are NOT sanitized in any way.
116 * @param string|string[] $args,...
119 public function unsafeParams( /* ... */ ) {
120 $args = func_get_args();
121 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
122 // If only one argument has been passed, and that argument is an array,
123 // treat it as a list of arguments
124 $args = reset( $args );
126 $this->command
.= implode( ' ', $args );
132 * Sets execution limits
134 * @param array $limits Optional array with limits(filesize, memory, time, walltime).
137 public function limits( array $limits ) {
138 $this->limits
= $limits +
$this->limits
;
144 * Sets environment variables which should be added to the executed command environment
146 * @param string[] $env array of variable name => value
149 public function environment( array $env ) {
156 * Sets calling function for profiler. By default, the caller for execute() will be used.
158 * @param string $method
161 public function profileMethod( $method ) {
162 $this->method
= $method;
168 * Controls whether stderr should be included in stdout, including errors from limit.sh.
169 * Default: don't include.
174 public function includeStderr( $yesno = true ) {
175 $this->useStderr
= $yesno;
181 * Sets cgroup for this command
183 * @param string|false $cgroup
186 public function cgroup( $cgroup ) {
187 $this->cGroup
= $cgroup;
193 * Executes command. Afterwards, getExitCode() and getOutput() can be used to access execution
198 * @throws ProcOpenError
199 * @throws ShellDisabledError
201 public function execute() {
202 $this->everExecuted
= true;
204 $profileMethod = $this->method ?
: wfGetCaller();
207 foreach ( $this->env
as $k => $v ) {
208 if ( wfIsWindows() ) {
209 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
210 * appear in the environment variable, so we must use carat escaping as documented in
211 * https://technet.microsoft.com/en-us/library/cc723564.aspx
212 * Note however that the quote isn't listed there, but is needed, and the parentheses
213 * are listed there but doesn't appear to need it.
215 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
217 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
218 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
220 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
224 $cmd = $envcmd . trim( $this->command
);
227 if ( is_executable( '/bin/bash' ) ) {
228 $time = intval( $this->limits
['time'] );
229 $wallTime = intval( $this->limits
['walltime'] );
230 // for b/c, wall time falls back to time
231 $wallTime = min( $time, $wallTime );
232 $mem = intval( $this->limits
['memory'] );
233 $filesize = intval( $this->limits
['filesize'] );
235 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
236 $cmd = '/bin/bash ' . escapeshellarg( __DIR__
. '/limit.sh' ) . ' ' .
237 escapeshellarg( $cmd ) . ' ' .
239 "MW_INCLUDE_STDERR=" . ( $this->useStderr ?
'1' : '' ) . ';' .
240 "MW_CPU_LIMIT=$time; " .
241 'MW_CGROUP=' . escapeshellarg( $this->cGroup
) . '; ' .
242 "MW_MEM_LIMIT=$mem; " .
243 "MW_FILE_SIZE_LIMIT=$filesize; " .
244 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
245 "MW_USE_LOG_PIPE=yes"
248 } elseif ( $this->useStderr
) {
251 } elseif ( $this->useStderr
) {
254 wfDebug( __METHOD__
. ": $cmd\n" );
256 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
257 // Other platforms may be more accomodating, but we don't want to be
258 // accomodating, because very long commands probably include user
259 // input. See T129506.
260 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN
) {
261 throw new Exception( __METHOD__
.
262 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
266 0 => [ 'file', 'php://stdin', 'r' ],
267 1 => [ 'pipe', 'w' ],
268 2 => [ 'pipe', 'w' ],
271 $desc[3] = [ 'pipe', 'w' ];
274 $scoped = Profiler
::instance()->scopedProfileIn( __FUNCTION__
. '-' . $profileMethod );
275 $proc = proc_open( $cmd, $desc, $pipes );
277 $this->logger
->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
278 throw new ProcOpenError();
280 $outBuffer = $logBuffer = '';
286 /* According to the documentation, it is possible for stream_select()
287 * to fail due to EINTR. I haven't managed to induce this in testing
288 * despite sending various signals. If it did happen, the error
289 * message would take the form:
291 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
293 * where [4] is the value of the macro EINTR and "Interrupted system
294 * call" is string which according to the Linux manual is "possibly"
295 * localised according to LC_MESSAGES.
297 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
298 $eintrMessage = "stream_select(): unable to select [$eintr]";
304 while ( $running === true ||
$numReadyPipes !== 0 ) {
306 $status = proc_get_status( $proc );
307 // If the process has terminated, switch to nonblocking selects
308 // for getting any data still waiting to be read.
309 if ( !$status['running'] ) {
315 $readyPipes = $pipes;
317 // clear get_last_error without actually raising an error
318 // from http://php.net/manual/en/function.error-get-last.php#113518
319 // TODO replace with clear_last_error when requirements are bumped to PHP7
320 set_error_handler( function () {
322 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
323 @trigger_error
( '' );
324 // @codingStandardsIgnoreEnd
325 restore_error_handler();
327 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
328 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
329 // @codingStandardsIgnoreEnd
330 if ( $numReadyPipes === false ) {
331 $error = error_get_last();
332 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
335 trigger_error( $error['message'], E_USER_WARNING
);
336 $logMsg = $error['message'];
340 foreach ( $readyPipes as $fd => $pipe ) {
341 $block = fread( $pipe, 65536 );
342 if ( $block === '' ) {
344 fclose( $pipes[$fd] );
345 unset( $pipes[$fd] );
349 } elseif ( $block === false ) {
351 $logMsg = "Error reading from pipe";
353 } elseif ( $fd == 1 ) {
355 $outBuffer .= $block;
356 } elseif ( $fd == 2 ) {
358 $errBuffer .= $block;
359 } elseif ( $fd == 3 ) {
361 $logBuffer .= $block;
362 if ( strpos( $block, "\n" ) !== false ) {
363 $lines = explode( "\n", $logBuffer );
364 $logBuffer = array_pop( $lines );
365 foreach ( $lines as $line ) {
366 $this->logger
->info( $line );
373 foreach ( $pipes as $pipe ) {
377 // Use the status previously collected if possible, since proc_get_status()
378 // just calls waitpid() which will not return anything useful the second time.
380 $status = proc_get_status( $proc );
383 if ( $logMsg !== false ) {
387 } elseif ( $status['signaled'] ) {
388 $logMsg = "Exited with signal {$status['termsig']}";
389 $retval = 128 +
$status['termsig'];
392 if ( $status['running'] ) {
393 $retval = proc_close( $proc );
395 $retval = $status['exitcode'];
398 if ( $retval == 127 ) {
399 $logMsg = "Possibly missing executable file";
400 } elseif ( $retval >= 129 && $retval <= 192 ) {
401 $logMsg = "Probably exited with signal " . ( $retval - 128 );
405 if ( $logMsg !== false ) {
406 $this->logger
->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
409 return new Result( $retval, $outBuffer, $errBuffer );